<template>
  <div>
    <el-switch v-model="dataInfo.gadgetSetting.isCenter"
               active-text="Is Center"></el-switch>
    <br>
    <el-switch v-model="dataInfo.gadgetSetting.isTextEdit"
               style="margin:10px auto"
               active-text="Html Code"
               @change="switchHandler"
               inactive-text="Quill Edit">
    </el-switch>
    <div v-if="!dataInfo.gadgetSetting.isTextEdit" class="quill_editor">
      <quill-editor 
                  style="height:315px"
                  ref="myTextEditor"
                  v-model="dataInfo.gadgetSetting.htmlValue"
                  :options="editorOption"></quill-editor>  
      <el-popover
        placement="bottom"
        trigger="click"
        popper-class="token_dialog"
       >
       <div>
        <div class="token_dialog_title">{{$t('quill.toolbar.token.title')}}</div>
        <el-input :placeholder="$t('quill.toolbar.token.search')"
                  prefix-icon="el-icon-search"
                  v-model="tokenSearchValue"
                  @input="tokenSearchInput">
        </el-input>
        <div class="token_dialog_list"
             v-if="tokenSearchList.length">
          <div class="token_dialog_list_item"
               v-for="item in tokenSearchList"
               :key="item.name"
               @click="insertFields(item.name)">{{item.label}}</div>
        </div>
      </div>
        <el-button  size="mini"
                type="primary"  
                class="token_dialog_btn"            
                plain slot="reference" style="padding: 7px; border: none;margin-bottom: 5px;">
                <span
                    class="cuifont icon_insert_token"
                    style="fontsize: 14px;"
                    ></span>
              </el-button>
      </el-popover> 
      

    </div>
    
    <div v-else>
      <el-popover
        placement="bottom"
        trigger="click"
        popper-class="token_dialog"
       >
       <div>
         <div class="token_dialog_title">{{$t('quill.toolbar.token.title')}}</div>
        <el-input :placeholder="$t('quill.toolbar.token.search')"
                prefix-icon="el-icon-search"
                v-model="tokenSearchValue"
                @input="tokenSearchInput">
        </el-input>
        <div class="token_dialog_list"
           v-if="tokenSearchList.length">
        <div class="token_dialog_list_item"
             v-for="item in tokenSearchList"
             :key="item.name"
             @click="insertNoteValue(item.name)">{{item.label}}</div>
        </div>
        </div>
        <el-button  size="mini"
                type="primary"
               
                plain slot="reference" style="padding: 7px; border: none;float:right;margin-bottom: 5px;">
                <span
                    class="cuifont icon_insert_token"
                    style="fontsize: 14px;"
                    ></span>
              </el-button>
      </el-popover>
      <el-input id="smsDetail"
                type="textarea"
                :rows="21"
                v-model="dataInfo.gadgetSetting.htmlValue">
      </el-input>
    </div>

  </div>
</template>

<script>
export default {
  components: {},
  data () {
    return {
      isTextEdit: false,
      isCenter: false,
      value: '',
      editorOption: {
        name: '',
        modules: {
          toolbar: {
            container: [
              ['code-block'],
              [{ 'direction': 'rtl' }],
              ['bold', 'italic', 'underline', 'strike'],
              [{ 'color': [] }],
              [{ 'background': [] }],
              [{ 'header': 1 }, { 'header': 2 }],
              [{ 'script': 'sub' }, { 'script': 'super' }],
              [{ 'list': 'ordered' }, { 'list': 'bullet' }],
              [{ 'indent': '-1' }, { 'indent': '+1' }],
              [{ 'font': ['sans-serif', 'monospace', 'serif'] }],
              [{ 'size': ['small', false, 'large', 'huge'] }],
              [{ 'align': [] }],
              ['link'],
              ['clean']
            ]
           
          }
        },
        theme: 'snow',
        placeholder: ''
      },
      tokenShow: false,
      tokenSearchValue: '',
      tokenSearchList: [],
      tokenSearchTimer: null,
      tokenList: [],
      inputTokenShow: false
    }
  },
  props: {
    dataInfo: {
      type: Object,
      default: function () {
        return {}
      }
    },
    fieldsList:[]
  },
  watch: {
    fieldsList: {
      handler(val) {
        this.tokenList = [
          {
            label: this.$t('quill.toolbar.token.CurrentDate'),
            name: 'CurrentDate'
          }
        ]
        val.forEach(item => {
          this.tokenList.push({
            label:`{${item.name}}`,
            name:`${item.name}`
          })
        });
        this.tokenSearchList = [...this.tokenList]
      },
      deep:true,
      immediate: true
    }
  },
  computed: {},
  created () {
    // this.tokenSearchList = [...this.tokenList]
  },
  mounted () {
    this.initButton()
  },
  methods: {
    switchHandler (e) {
      this.tokenShow = false
      this.inputTokenShow = false
      this.dataInfo.gadgetSetting.htmlValue = null
    },
    changeManyMeasure (val) {
      if (val) {
        this.setting.valueFieldsNameMeasureY = ''
        this.setting.valueFieldsNameManyY = []
      } else {
        this.setting.valueFieldsNameManyY = []
      }
      this.$forceUpdate()
    },
    getData () {
      return this.setting
    },
    initButton () {
      const dom = document.querySelector('.ql-insertMetric')
      dom.innerHTML = `<el-button      size="mini"
                      type="primary"
                      plain
                      slot="reference"
                      style="padding: 7px; border: none;float:right;">
                       <span
                        class="cuifont icon_insert_token"
                        style="fontsize: 14px;"
                      ></span>`
    },
    tokenSearchInput (value) {
      if (this.tokenSearchTimer) {
        clearTimeout(this.tokenSearchTimer)
      }
      this.tokenSearchTimer = setTimeout(() => {
        this.tokenSearchList = this.tokenList.filter(v => v.name.toLowerCase().includes(value.toLowerCase()))
      }, 1000)
    },
    handleToken () {
      this.tokenShow = !this.tokenShow
    },
    insertFields (value) {
      if (!value) {
        return false
      }
      const quillSelf = this.$refs.myTextEditor.quill
      quillSelf.focus()
      let selection = quillSelf.getSelection()
      let nowIndex = 0
      if (selection) {
        nowIndex = selection.index
      }
      quillSelf.clipboard.dangerouslyPasteHTML(nowIndex, `{${value}}`)
      this.tokenShow = false
    },
    async insertNoteValue (val) {
      var myValue = `{${val}}`
      const myField = document.querySelector('#smsDetail');
      myField.focus()
      if (myField.selectionStart || myField.selectionStart === 0) {
        var startPos = myField.selectionStart //选区开始位置
        var endPos = myField.selectionEnd //选区结束位置
        this.dataInfo.gadgetSetting.htmlValue = myField.value.substring(0, startPos) + myValue + myField.value.substring(endPos, myField.value.length)
        await this.$nextTick() //修改数据之后立即使用这个方法获取更新后的DOM。
        myField.setSelectionRange(endPos + myValue.length, endPos + myValue.length)
      } else {
        this.dataInfo.gadgetSetting.htmlValue += myValue
      }
      this.inputTokenShow = false
    },
  }
}
</script>

<style lang="scss">

.quill_editor {
  position: relative;
  .token_dialog_btn {
    position: absolute;
    top: 3px;
    right:10px
  }
}

.token_dialog {
  width: 300px;
  min-height: 200px;
  max-height: 500px;
  overflow-y: scroll;
  z-index: 999;
  background-color: #ffffff;
  padding: 10px;
  border: 1px solid #ccc;
  &_title {
    font-weight: bold;
    margin-bottom: 5px;
  }
  &_list {
    &_item {
      padding: 5px;
      cursor: pointer;
    }
  }    
 }
</style>
